﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AnalysisServices.AdomdClient;

using System.ComponentModel;

namespace MDX_Studio_v2
{
	public partial class MainForm
	{

		private BackgroundWorker _worker;

		private void DoIt()
		{
			toolstrip_Execute.Enabled = false;
			toolstrip_CancelExecution.Enabled = true;

			try
			{
				_worker = new BackgroundWorker();
				_worker.WorkerSupportsCancellation = true;
				_worker.WorkerReportsProgress = true;
				_worker.DoWork += new DoWorkEventHandler(worker_DoWork);
				_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
				_worker.RunWorkerAsync();
			}
			catch (Exception ex)
			{
				//Console.WriteLine(ex.Message);
				_resultWindow.AddDebug(ex.Message);
			}
		}

		private void worker_DoWork(object sender, DoWorkEventArgs e)
		{
			BackgroundWorker worker = sender as BackgroundWorker;


			if (worker.CancellationPending == true)
			{
				e.Cancel = true;
			}
			else
			{
				// Perform a time consuming operation and report progress.
				e.Result = ExecuteQuery();
				_resultWindow.AddDebug("Hit Execution");
				//Console.WriteLine("Hit Execution");
			}
			
		}

		void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			if (e.Result != null)
			{
				CellSet set = (CellSet)e.Result;
				_resultWindow.Results = set;
				PropagateContext();

				toolstrip_CancelExecution.Enabled = false;
				toolstrip_Execute.Enabled = true;
				_resultWindow.AddDebug("Finished Execution");
			}
		}

		private CellSet ExecuteQuery()
		{
			

			try
			{
				_Context.Connection.StartQueryConnection();
				AdomdConnection queryConn = _Context.Connection.QueryConnection;
				AdomdCommand command = queryConn.CreateCommand();

				// Create the command
				command = queryConn.CreateCommand();
				command.CommandText = _parametersWindow.ParsedQuery;

				// Perf
				_Context.PerfStats.Start(_Context.Connection.ServerName, "2008");
				Console.WriteLine("Doing Perfmon");
				CellSet set = command.ExecuteCellSet();
				_Context.PerfStats.Finish();

				// Update
				return set;
			}
			catch (Exception ex)
			{
				Console.WriteLine("MainForm_Execute.cs\\ExecuteQuery: {0}", ex.Message);
				_resultWindow.AddMessage(ex.Message);
				return null;
			}
		}

		private void ClearCache()
		{
			toolstrip_Execute.Enabled = false;

			try
			{
				_Context.Connection.StartQueryConnection();
				AdomdConnection queryConn = _Context.Connection.QueryConnection;
				AdomdCommand command = queryConn.CreateCommand();

				// Clear Cache
				string format = "<Batch xmlns=\"http://schemas.microsoft.com/analysisservices/2003/engine\"><ClearCache><Object><DatabaseID>{0}</DatabaseID><CubeID>{1}</CubeID></Object></ClearCache></Batch>";
				string str_ClearCache = string.Format(format, _Context.Connection.Catalog, _Context.Connection.Cube);
				command.CommandText = str_ClearCache;
				command.ExecuteNonQuery();


				// Update
				//_resultWindow.Results = set;
				//PropagateContext();
				_resultWindow.AddMessage(_Context.Connection.Cube + " cache cleared.", false);
			}
			catch (Exception ex)
			{
				Console.WriteLine("MainForm_Execute.cs\\ClearCache: {0}", ex.Message);
				_resultWindow.AddMessage(ex.Message);
			}
			toolstrip_Execute.Enabled = true;
		}

		public void AddResultMessage(string message, bool isError=false)
		{
			_resultWindow.AddMessage(message, isError);
		}
	}

}
